<template>
  <!-- 新增、修改质控点 -->
  <div class="add-point-dialog">
    <el-dialog :title="addParams.title" :visible.sync="addParams.visible" :close-on-click-modal="false" width="80%">
      <el-form :model="formData" :rules="rules" :disabled="addParams.type === 'detail'" ref="formData" label-width="120px" label-position="right" class="point-form">
        <!-- 基础信息 -->
        <div>
          <div class="title">基础信息</div>
          <div class="form_flex">
            <el-form-item label="一级指标" prop="indexOne">
              <el-select v-model="formData.indexOne" filterable placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in indexOneArr" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级指标" prop="indexTwo">
              <el-input v-model="formData.indexTwo" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="三级指标" prop="indexThree">
              <el-input v-model="formData.indexThree" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="质控点" prop="name">
              <el-input v-model="formData.name" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="质控点内涵" prop="intension">
              <el-input v-model="formData.intension" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="诊断标准" prop="diagnosisStandard">
              <el-input v-model="formData.diagnosisStandard" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="质控点类别" prop="chargeCategory">
              <el-select v-model="formData.chargeCategory" filterable placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in pointCategoryArr" :key="item.id" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="质控点类型" prop="chargeType">
              <el-select v-model="formData.chargeType" filterable placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in pointTypeArr" :key="item.id" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="值类型" prop="valueType">
              <el-select v-model="formData.valueType" placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in pointValueTypeArr" :key="item.id" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预期值" prop="expectedValue">
              <el-select v-model="formData.expectedValue" placeholder="请选择值预期" :disabled="!isEdit">
                <el-option v-for="(item,index) in expectedValueArr" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="权重" prop="weight">
              <el-input v-model="formData.weight" :disabled="!isEdit"></el-input>
            </el-form-item>
            <el-form-item label="责任部门" prop="belongPart">
              <el-select v-model="formData.belongPart" filterable clearable placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in organizeArr" :key="item.id" :label="item.orgName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <template v-if="addParams.pointType === 'target'">
              <el-form-item label="标准值" prop="standardValue">
                <el-input v-model="formData.standardValue" :disabled="!isEdit&&formData.isOptional===1"></el-input>
              </el-form-item>
              <el-form-item label="目标值" prop="targetValue">
                <el-input v-model="formData.targetValue"></el-input>
              </el-form-item>
            </template>
            <template v-if="addParams.pointType === 'show'">
              <el-form-item label="标准值" prop="standardValue">
                <el-input v-model="formData.standardValue" :disabled="!isEdit"></el-input>
              </el-form-item>
              <el-form-item label="目标值" prop="targetValue">
                <el-input v-model="formData.targetValue" :disabled="!isEdit"></el-input>
              </el-form-item>
            </template>
            <template v-if="addParams.pointType === 'myTarget'">
              <el-form-item label="标准值" prop="standardValue">
                <el-input v-model="formData.standardValue"></el-input>
              </el-form-item>
              <el-form-item label="目标值" prop="targetValue">
                <el-input v-model="formData.targetValue"></el-input>
              </el-form-item>
            </template>
            <template v-if="addParams.showNote">
              <el-form-item label="备注" prop="targetDesc">
                <el-input v-model="formData.targetDesc"></el-input>
              </el-form-item>
            </template>
            <template v-if="addParams.optional">
              <el-form-item label="是否可选" prop="isOptional">
                <el-select v-model="formData.isOptional" filterable placeholder="请选择" :disabled="!isEdit">
                  <!-- <el-option label="未选" :value="0"></el-option> -->
                  <el-option label="必选" :value="1"></el-option>
                  <el-option label="可选" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </div>
        </div>

        <!-- 状态值采集 -->
        <div>
          <div class="title">状态值采集</div>
          <div class="form_flex">
            <el-form-item label="采集方式" prop="collectMode">
              <el-select v-model="formData.collectMode" filterable clearable placeholder="请选择" :disabled="!isEdit">
                <el-option label="填报" :value="1"></el-option>
                <el-option label="自动采集" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="算法名称" prop="algorithmId">
              <el-select v-model="formData.algorithmId" filterable clearable placeholder="请选择" @change="changeAlgorithm" :disabled="!isEdit">
                <el-option v-for="item in allAlgorithmArr" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="算法版本" prop="algorithmVersionId">
              <el-select v-model="formData.algorithmVersionId" filterable clearable placeholder="请选择" :disabled="!isEdit">
                <el-option v-for="item in allAlgorithmVersionArr" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="算法说明" prop="algorithmDesc" class="response">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" disabled v-model="algorithmDesc"></el-input>
            </el-form-item>
          </div>
        </div>

        <!-- 预警规则 -->
        <div>
          <div class="title">预警规则</div>
          <div class="form_flex">
            <el-form-item label="是否预警" prop="isWarning">
              <!-- :disabled="!isEdit" -->
              <el-radio-group v-model="formData.isWarning" @change="clearValidate('formData')">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="预警标题" prop="warningTitile" :rules="formData.isWarning===1? [{
                                required: true,
                                message: '请输入预警标题',
                                trigger: 'blur'
                                }]: []">
              <!-- :disabled="!isEdit" -->
              <el-input v-model="formData.warningTitile"></el-input>
            </el-form-item>
            <el-form-item label="预警条件" prop="warningFactor" :rules="formData.isWarning===1? [{
                                required: false,
                                message: '请选择预警条件',
                                trigger: 'blur'
                                }]: []">
              <!--  :disabled="!isEdit" -->
              <el-select v-model="formData.warningFactor" filterable placeholder="请选择">
                <el-option v-for="item in warningFactorArr" :key="item.id" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="阈值" prop="warningThreshold" :rules="formData.isWarning===1? [{
                                required: false,
                                message: '请输入阈值',
                                trigger: 'blur'
                                }]: []">
              <!-- :disabled="!isEdit" -->
              <el-input v-model="formData.warningThreshold"></el-input>
            </el-form-item>
            <el-form-item label="预警开始时间" prop="warningStartTime" :rules="formData.isWarning===1? [{
                                required: true,
                                message: '请选择预警开始时间',
                                trigger: 'blur'
                                }]: []">
              <!-- :disabled="!isEdit" -->
              <el-date-picker v-model="formData.warningStartTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预警结束时间" prop="warningEndTime" :rules="formData.isWarning===1? [{
                                required: true,
                                message: '请选择预警结束时间',
                                trigger: 'blur'
                                }]: []">
              <!-- :disabled="!isEdit" -->
              <el-date-picker v-model="formData.warningEndTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预警检查频率" prop="warningRate" :rules="formData.isWarning===1? [{
                                required: true,
                                message: '请输入预警检查频率',
                                trigger: 'blur'
                                }]: []">
              <!-- :disabled="!isEdit" -->
              <el-input v-model.trim="formData.warningRate">
                <template slot="append">天 / 次</template>
              </el-input>
            </el-form-item>
            <!--<el-form-item label="预警消息模板" prop="warningModule" class="response">-->
            <!--<el-input v-model="formData.warningModule"></el-input>-->
            <!--</el-form-item>-->
          </div>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer" v-if="addParams.type !='detail'">
        <el-button @click="addParams.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('formData')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getStorage } from '../../../../config/utils'
import { getAllAlgorithm, getVersionAll, getAllUser, getAllOrganize } from '../../../../api/systemManage'
import { updateWaitDealState } from '@/api'
import { updateTargetValue } from '../../../../api/target'

export default {
  name: 'addPointDialog',
  props: {
    addParams: {
      type: Object
    },
    pointForm: {
      type: Object
    },
    orgId: {
      type: String,
      default: ''
    }
  },
  computed: {
    pointTypeArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.pointType)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    },
    pointCategoryArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.pointCategory)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    },
    pointValueTypeArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.pointValueType)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    },
    warningFactorArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.warningFactor)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    },
    indexOneArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.xtWZ)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    },
    expectedValueArr() {
      const systemInfo = getStorage('systemInfo')
      if (systemInfo && systemInfo.length) {
        const temp = systemInfo.filter(item => item.code === this.$config.pointZYQ)
        if (temp && temp.length) {
          return temp[0].dictValDTOList
        }
      }
      return []
    }
  },
  data() {
    var validateWarning = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择预警标题'))
      }
    }
    return {
      formData: {
        indexOne: '',
        indexTwo: '',
        indexThree: '',
        chargeType: '',
        chargeCategory: '',
        intension: '',
        diagnosisStandard: '',
        name: '',
        warningFactor: '',
        algorithmVersionId: '',
        warningThreshold: '',
        warningTitile: '质控点完成进度预警',
        expectedValue: '',
        weight: 0,
        belongPart: '',
        isOptional: null,
        targetDesc: '',
        collectMode: 1,
        isWarning: 1,
        warningRate: 60,
        warningStartTime: '',
        warningEndTime: ''
      },
      allAlgorithmArr: [],
      allAlgorithmVersionArr: [],
      // allUser: [],
      algorithmDesc: '', // 算法说明，选择算法名称后自动回显
      rules: {
        indexOne: [{ required: true, message: '请输入一级指标', trigger: 'blur' }],
        indexTwo: [{ required: true, message: '请输入二级指标', trigger: 'blur' }],
        chargeType: [{ required: true, message: '请选择质控点类型', trigger: 'change' }],
        // warningFactor: [
        //     {required: true, message: '请选择预警条件', trigger: 'change'}
        // ],
        warningModule: [{ required: true, message: '请输入预警消息模板', trigger: 'change' }],
        algorithmId: [{ required: true, message: '请选择算法名称', trigger: 'change' }],
        intension: [{ required: true, message: '请输入质控点内涵', trigger: 'blur' }],
        diagnosisStandard: [{ required: true, message: '请输入诊断标准', trigger: 'blur' }],
        name: [{ required: true, message: '请输入质控点', trigger: 'blur' }],
        // warningTitile: [
        //     {validator: validateWarning, trigger: 'blur' }
        // ],
        // warningThreshold: [
        //     {required: true, message: '请输入阈值', trigger: 'blur'}
        // ],
        valueType: [{ required: true, message: '请选择值类型', trigger: 'change' }],
        algorithmVersionId: [{ required: true, message: '请选择算法版本', trigger: 'change' }],
        expectedValue: [{ required: true, message: '请输入预期值', trigger: 'change' }],
        weight: [{ required: true, message: '请输入权重', trigger: 'blur' }],
        belongPart: [{ required: true, message: '请选择责任部门' }],
        isOptional: [{ required: true, message: '请选择质控点是否可选', trigger: 'blur' }],

        isWarning: [{ required: true, message: '请选择是否预警' }]
      },
      // 责任部门
      organizeArr: [],
      isEdit: true // 是否可以修改
    }
  },
  async created() {
    if (this.addParams.pointType === 'target') {
      // 自定义可修改所有字段，下发的只能修改目标值
      this.isEdit = this.addParams.isCustomPoint
    } else {
      this.isEdit = true
    }
    await this.getAllAlgorithm()
    // await this.getAllUser();
    this.getOrganize()

    // 设置默认预警时间
    const year = new Date().getFullYear()
    this.formData.warningStartTime = `${year}-06-01 00:00:00`
    this.formData.warningEndTime = `${year}-12-01 00:00:00`
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = { ...this.formData }
          params.targetStandardId = this.addParams.targetStandardId
          if (this.addParams.pointType === 'target') {
            this.setTargetValue(params)
          } else {
            this.$emit('addOrEdit', this.addParams.type, params)
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    clearValidate(formName) {
      this.$refs[formName].clearValidate(['warningTitile', 'warningFactor', 'warningThreshold', 'warningStartTime', 'warningEndTime', 'warningRate'])
    },
    // 获取算法名称下拉数据
    getAllAlgorithm() {
      getAllAlgorithm()
        .then(res => {
          this.allAlgorithmArr = res || []
        })
        .catch(() => {})
    },
    // 获取算法版本下拉数据
    getAllAlgorithmVersion(algorithmId) {
      getVersionAll({ algorithmId: algorithmId })
        .then(res => {
          this.allAlgorithmVersionArr = res || []
        })
        .catch(() => {})
    },
    // 选择算法名称
    changeAlgorithm(val) {
      const temp = this.allAlgorithmArr.filter(item => item.id === val)
      if (temp && temp.length) {
        this.algorithmDesc = temp[0].desc
        this.getAllAlgorithmVersion(val)
      }
    },
    // 获取接收人下拉数据
    // getAllUser () {
    //     getAllUser().then(res => {
    //         this.allUser = res || [];
    //     }).catch(() => {})
    // },
    // 获取责任部门下拉数据
    getOrganize() {
      // console.log(this.addParams.joinOrgDTOList);
      getAllOrganize()
        .then(res => {
          // console.log(res);
          this.organizeArr = !this.addParams.joinOrgDTOList
            ? res
            : res.filter(organize => {
                for (const org of this.addParams.joinOrgDTOList) {
                  if (organize.id === org.relationId) {
                    return true
                  }
                }
                return false
              })
          if (this.orgId) {
            this.formData.belongPart = this.orgId
          }
        })
        .catch()
    },
    // 弹框修改目标值
    setTargetValue(data) {
      const params = {
        id: data.id,
        targetValue: data.targetValue,
        targetDesc: data.targetDesc,
        indexOne: data.indexOne,
        indexTwo: data.indexTwo,
        indexThree: data.indexThree,
        chargeType: data.chargeType,
        chargeCategory: data.chargeCategory,
        intension: data.intension,
        diagnosisStandard: data.diagnosisStandard,
        name: data.name,
        warningFactor: data.warningFactor,
        algorithmVersionId: data.algorithmVersionId,
        warningThreshold: data.warningThreshold,
        warningTitile: '质控点完成进度预警',
        expectedValue: data.expectedValue,
        weight: data.weight,
        belongPart: data.expectedValue,
        isOptional: data.isOptional,
        collectMode: data.collectMode,
        isWarning: data.isWarning,
        warningRate: data.warningRate,
        warningStartTime: data.warningStartTime,
        warningEndTime: data.warningEndTime
      }
      updateTargetValue(params)
        .then(res => {
          this.$message.success('操作成功')
          this.$emit('getList')
          this.addParams.visible = false
          if (this.addParams.isWaitDeal) {
            updateWaitDealState(this.addParams.waitDealId, 1)
          }
        })
        .catch(() => {})
    }
  },
  watch: {
    addParams: {
      handler(val) {
        if (this.addParams.type != 'add') {
          this.formData = { ...val.data }
          if (this.formData.algorithmId) {
            this.getAllAlgorithmVersion(this.formData.algorithmId)
          }
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.add-point-dialog {
  .title {
    font-weight: bold;
    font-size: 14px;
    padding: 10px 0;
    margin: 10px;
    border-bottom: 1px solid $lineColor;
  }

  .point-form {
    /*display: flex;*/
    /*flex-wrap: wrap;*/
    .form_flex {
      display: flex;
      flex-wrap: wrap;
    }
    .el-form-item {
      width: 33%;
      input,
      select {
        width: 100% !important;
      }
    }
  }
}
</style>
